﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CNotebook.Inventory
{
    public class RevaluationManager:ConnectionManager
    {
        public SqlException Add(RevaluationUnit oUnit)
        {
            SqlCommand oCommand = new SqlCommand();

            try
            {
                oCommand.Connection = this.Connection;
                oCommand.CommandText = "INSERT INTO OREVAL (DocNum, Remarks, PostingDate) VALUES (@DocNum, @Remarks, @PostingDate)";
                oCommand.Parameters.Add(new SqlParameter("@DocNum", oUnit.DocumentNumber));
                oCommand.Parameters.Add(new SqlParameter("@Remarks", oUnit.Remarks));
                oCommand.Parameters.Add(new SqlParameter("@PostingDate", oUnit.PostingDate));

                oCommand.ExecuteNonQuery();

                foreach (DataRow oRow in oUnit.LineItems.Rows)
                {
                    oCommand = new SqlCommand();
                    oCommand.Connection = this.Connection;

                    oCommand.CommandText = "INSERT INTO REVAL1 (WhseCode, ItemCode, ItemName, CurrentCost, NewCost) values (@WhsCode, @ItemCode, @ItemName, @CurrentCost, @NewCost)";

                    oCommand.Parameters.Add(new SqlParameter("@WhsCode", oRow["WhseCode"].ToString()));
                    oCommand.Parameters.Add(new SqlParameter("@ItemCode", oRow["ItemCode"].ToString()));
                    oCommand.Parameters.Add(new SqlParameter("@ItemName", oRow["ItemName"].ToString()));
                    oCommand.Parameters.Add(new SqlParameter("@CurrentCost", Convert.ToDouble(oRow["CurrentCost"])));
                    oCommand.Parameters.Add(new SqlParameter("@NewCost", Convert.ToDouble(oRow["NewCost"].ToString())));

                    oCommand.ExecuteNonQuery();

                }


                return null;
            }
            catch (SqlException ex)
            {
                return ex;
            }
            finally
            {
                oCommand.Dispose();
            }
            
        }
    }
}
